<template>
	<div class="home container" id="fullscreen-container" ref="fullscreen">
		<slot name="search"></slot>
		<slot name="menu"></slot>
		<div id="popup" class="ol-popup">
			<a href="#" id="popup-closer" class="ol-popup-closer"></a>
			<div id="popup-content"></div>
		</div>
		<!-- 在 template 部分修改弹窗结构 -->
		<div id="popuptable" class="ol-popup">
			<a href="#" id="popuptable-closer" class="ol-popup-closer"></a>
			<div id="popuptable-content">
				<!-- 表格结构 -->
				<table class="data-table">
					<thead>
						<tr>
							<th>指标</th>
							<th>数值</th>
						</tr>
					</thead>
					<tbody></tbody>
				</table>
			</div>
		</div>
		<div class="controlbox">
			<el-tooltip class="item" effect="dark" content="绘制矩形" placement="left-start">
				<i class="juxing" style="color:blue;margin-top: 10px;" @click="juxingHandler"></i>
			</el-tooltip>
			<el-tooltip class="item" effect="dark" content="停止绘制" placement="left-start">
				<i class="stopdraw" style="color:yellowgreen;margin-top: 10px;" @click="endModify"></i>
			</el-tooltip>
			<el-tooltip class="item" effect="dark" content="清楚绘制" placement="left-start">
				<i class="clear" style="color:yellowgreen;margin-top: 10px;" @click="clearHandler"></i>
			</el-tooltip>
		</div>
		<div id="map" :style="{ 'width': mapWidth, 'height': mapHeight }"></div>
		<el-tooltip ref="elTooltip" :append-to-body="false" class="item" effect="light" placement="left">
			<div slot="content">
				<div class="mapbox">
					<li @click="mapChangeHandler('0')" :class="models.active[0] ? 'activeStyle' : ''">
						<img src="../assets/image/dixing.jpg" width="100px" height="50px">
						<div class="on">地形地图</div>
					</li>
					<li @click="mapChangeHandler('1')" :class="models.active[1] ? 'activeStyle' : ''">
						<img src="../assets/image/yingxiang.jpg" width="100px" height="50px">
						<div class="on">影像地图</div>
					</li>
					<li @click="mapChangeHandler('2')" :class="models.active[2] ? 'activeStyle' : ''">
						<img src="../assets/image/yingxiang.jpg" width="100px" height="50px">
						<div class="on">离线影像</div>
					</li>
				</div>
			</div>
			<div class="map0"></div>
		</el-tooltip>
	</div>
</template>
<script lang="ts">

import GeoJSON from "ol/format/GeoJSON";
import { Component, Vue, Prop, Ref } from 'vue-property-decorator';
import { Feature, Overlay } from "ol";
import { boundingExtent} from "ol/extent";
import { Point } from "ol/geom";
import EChartsLayer from 'ol-echarts';
import { drawBox, stopDraw, findFeaturesInGeometry } from '@/utils/map'

import {
	createMap, mapChangeType,
	createSource,
	createStyle,
	createLayer,
	pointImageStyle

} from '@/utils/map'
@Component({})
export default class AppMap extends Vue {

	@Ref('fullscreen') private fullscreen!: any;
	@Ref('elTooltip') private elTooltip!: any;

	models: any = {
		map: null,
		mapLanLot: [111.670801, 40.818311],
		geoJsonSource: createSource(),
		active: [true, false, false],
		draw: null,
		polygonSource: createSource(),
		chartLayer: null,
	};

	@Prop() private mapWidth!: string;
	@Prop() private mapHeight!: string;
	popupElement: any;
	popupElementTable: any;
	popupContent: any;
	popupTableContent: any;
	popupOverlay: any;
	popupOverlayTable: any;
	showChart = false;
	currentFeature:any;



	initMap() {
		this.models.map = createMap([111.670801, 40.818311]);
		this.models.map.addLayer(createLayer(this.models.geoJsonSource, createStyle("transparent", "darkgreen", "red")));
		this.models.map.addLayer(createLayer(this.models.polygonSource, createStyle("transparent", "green", "red")));
		this.popupElement = document.getElementById('popup');
		this.popupContent = document.getElementById('popup-content');
		this.popupTableContent = document.getElementById('popuptable-content');
		this.popupElementTable = document.getElementById('popuptable');
		const tablecloser = document.getElementById('popuptable-closer');
		this.popupOverlay = new Overlay({
			element: this.popupElement,
			positioning: 'bottom-center',
			stopEvent: false // 阻止地图事件穿透
		});
		this.models.map.addOverlay(this.popupOverlay);

		this.popupOverlayTable = new Overlay({
			element: this.popupElementTable,
			positioning: 'bottom-center',

		});
		this.models.map.addOverlay(this.popupOverlayTable);
		if (tablecloser) {
			tablecloser.addEventListener('click', (evt) => {
			this.popupOverlayTable.setPosition(undefined);
			this.popupElementTable.style.display = 'none';
			evt.preventDefault();
			evt.stopPropagation(); // 阻止事件冒泡
			});
		}
	}

	mapChangeHandler(x) {
		mapChangeType(this.models.map.getLayers(), x, this.models.active);
		this.$message.success("成功切换底图");
	}

	findFeature() {

		const features = this.models.polygonSource.getFeatures();
		if (features.length === 0) {
			this.$message.info("请绘制一个区域");
			return;
		}
		let findF: any = [];
		for (let ft of features) {
			findF = findF.concat(findFeaturesInGeometry(ft.getGeometry(), this.models.geoJsonSource));
		}
		if (findF.length > 0) {
			const m = findF.map((f: any) => f.get("id"));
			return m;
		}
		return [];
	}

	endModify() {
		stopDraw({
			map: this.models.map,
			draw: this.models.draw,
		});
		this.$message.success("已停止绘制,可以随意操作地图区域");
	}

	clearHandler() {
		this.$confirm('确定要清除已绘制的数据吗？', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			this.endModify();
			this.models.polygonSource.clear();
			if (this.models.chartLayer) {
				this.models.chartLayer.remove();
				this.models.chartLayer = null;
			}
			this.$message.success("已清楚绘制内容");
		});
	}

	buildChartIndex(dataList) {
		// 1. 彻底销毁旧图层（关键修复点）
		if (this.models.chartLayer) {

			this.models.chartLayer.remove();
			this.models.chartLayer = null;
		}
		if (dataList === null || dataList.length === 0 || dataList.series == null) {
			this.$message.info("没有指标数据");
			return;
		}

		const scatterData = dataList.series.map((school: any) => {
			// 关键点 1：确保坐标转换为数字类型
			const lng = parseFloat(school.coordinates[0]);
			const lat = parseFloat(school.coordinates[1]);

			return {
				name: school.name,
				value: [lng, lat], // 坐标必须为数字
				itemData: {        // 自定义数据字段
					category: school.category,
					values: school.data.map((v: string) => parseInt(v)) // 转换为数字
				}
			};
		});

		const chartOption = {
			tooltip: {
				trigger: 'item',
				formatter: (params: any) => {
					const data = params.data.itemData;
					return `
				${params.name}<br/>
				${data.category[0]}: ${data.values[0]}<br/>
				${data.category[1]}: ${data.values[1]}
			`;
				}
			},
			visualMap: { // 添加视觉映射增强可视化
				min: 0,
				max: 10,
				calculable: true,
				inRange: {
					color: ['#50a3ba', '#eac763', '#d94e5d']
				},
				left: '10%'
			},
			series: [{
				type: 'scatter',
				coordinateSystem: 'ol', // 必须声明坐标系
				data: scatterData,
				symbolSize: 20,
				encode: { // 明确数据绑定
					lng: 0,
					lat: 1
				},
				itemStyle: {
					borderWidth: 2,
					borderColor: '#fff'
				}
			}]
		};

		// 初始化图层
		this.models.chartLayer = new EChartsLayer(chartOption, {
			projection: 'EPSG:4326',
			map: this.models.map,
			sysCoord: 'ol'
		});
		this.models.chartLayer.appendTo(this.models.map);
		this.models.map.render();

		setTimeout(() => {
			console.log(this.models.chartLayer)
			if (this.models.chartLayer?.$chart) {
				this.models.chartLayer.$chart.on('click', (params: any) => {
					const school = params.data;
					this.showSchoolTable(school);
				});
			}
		}, 100);

		const coordinates = dataList.series.map((s: any) => s.coordinates.map(parseFloat));
		const extent = boundingExtent(coordinates);
		this.models.map.getView().fit(extent, {
		padding: [50, 50, 50, 50],
		duration: 1000
		});
	}


	getChartOptions(type: string, formatter: any) {
		// 定义全局颜色主题（可自定义）
		const colorPalette = [
			'#5470c6', '#91cc75', '#fac858', '#ee6666',
			'#73c0de', '#3ba272', '#fc8452', '#9a60b4'
		];

		const options: any = {
			color: colorPalette, // 全局颜色，系列自动循环使用
			tooltip: {
				trigger: 'axis',
				axisPointer: { type: type },
				formatter: formatter,
			},
			grid: [],
			xAxis: [],
			yAxis: [],
			series: []
		};
		return options;
	}
	getChart(type: string, formatter: any, series: any[], axis?: any) {
		const options = this.getChartOptions(type, formatter);

		series.forEach(function (item, index) {
			if (!item.data) {
				return;
			}
			const coloredData = item.data.map((value: number, dataIndex: number) => ({
				value: value,
				itemStyle: {
					color: options.color[dataIndex % options.color.length] // 按数据索引取色
				}
			}));
			options.grid.push({
				show: true,
				containLabel: false,
				borderWidth: 0,
				borderColor: 'green',
				width: 300,    // 加宽 grid 区域（原 70）
				height: 120,
				left: '5%',      // 左侧留白
				right: '5%',     // 右侧留白
				bottom: '15%'
			});

			// xAxis 配置（移除 itemStyle 和 nameTextStyle 的颜色设置）
			options.xAxis.push({
				type: 'category',
				gridIndex: index,
				axisLine: { show: false },
				axisLabel: {
					interval: 0,
					rotate: 45,
					color: 'darkgreen', // 统一坐标轴标签颜色
					fontSize: 10
				},
				axisTick: { show: false },
				data: axis || item.category
			});

			// yAxis 配置保持简洁
			options.yAxis.push({
				type: 'value',
				show: true,
				min: 0.001,
				splitLine: { show: false },
				axisLabel: {
					show: false
				},
				axisLine: {
					show: false,
					onZero: false
				},
				nameGap: '1',
				axisTick: {
					show: false
				},
				nameTextStyle: {
					color: '#3c3c3c',
					fontSize: 14
				},
				gridIndex: index,

			});

			// 确保系列使用全局颜色（按索引自动循环）
			options.series.push({
				...item,
				data: coloredData, // 替换为带颜色的数据
				barWidth: 30,  // 柱子宽度基于 category 自动计算（原 15）
				barCategoryGap: '100%' // 柱子间距（默认 20%，越大间距越大）
			});
			console.log(options.series)
		});

		return options;
	}

	// 新增方法：显示学校数据表格
	showSchoolTable(school: any) {

		const tbody = this.popupTableContent.querySelector('tbody');
		tbody.innerHTML = school.itemData.category.map((cat: string, index: number) => `
			<tr>
			<td>${cat}</td>
			<td>${school.itemData.values[index]}</td>
			</tr>
		`).join('');

		// 定位弹窗
		this.popupOverlayTable.setPosition(school.value);
		this.popupElementTable.style.display = 'block';
		this.popupElementTable.style.opacity = '1'; // 强制显示

		// 自动居中视图
		this.models.map.getView().animate({
			center: school.value,
			zoom: 14,
			duration: 1000
		});
	}

	juxingHandler() {
		this.$message.success("开始绘制矩形区域，在地图区域点击之后移动鼠标即可，如果绘制完成请点击停止绘制按钮");
		this.models.draw = drawBox({
			map: this.models.map,
			draw: this.models.draw,
			source: this.models.polygonSource,
			drawType: 'Circle',
		})
	}

	searchFeature(searchValue) {
		searchValue = searchValue.trim().toLowerCase();
		var features = this.models.geoJsonSource.getFeatures();
		var matchedFeatures: any = [];

		// 清空弹窗
		this.popupOverlay.setPosition(undefined);
		this.popupElement.style.display = 'none';

		// 检索匹配要素
		features.forEach((feature: any) => {
			var propValue = feature.get('name') || '';
			if (propValue.toLowerCase().includes(searchValue) && feature.getGeometry().getType() === 'Point') {
				matchedFeatures.push(feature);
			}
		});

		// 处理结果
		if (matchedFeatures.length > 0) {
			// 显示第一个匹配项的弹窗
			var firstFeature = matchedFeatures[0];
			var geometry = firstFeature.getGeometry();
			var coord = geometry.getCoordinates();
			this.updatePosition(coord);
			// 填充弹窗内容
			this.popupContent.innerHTML = `<h4 sytle="cusor:pointer">${firstFeature.get('name')}</h4>
				<p>坐标: ${coord}</p>`;
			this.popupContent.

				//${firstFeature.get('id')}

				// 定位弹窗并显示
				this.popupOverlay.setPosition(coord);
			this.popupElement.style.display = 'block';

			// 定位地图视图到要素
			this.models.map.getView().fit(geometry.getExtent(), {
				padding: [50, 50, 50, 50],
				duration: 500
			});
		} else {
			this.$message('未找到匹配要素！');
		}
	}

	showData(id) {
		console.log(id)
	}
	setOpacity() {
		this.models.polygonLayer.setStyle(createStyle("transparent", "darkgreen", "red"))
	}

	noOpacity() {
		this.models.polygonLayer.setStyle(createStyle("orange", "darkgreen", "red"))
	}

	mounted() {
		this.initMap();
		this.fullscreen.appendChild(this.elTooltip.popperVM.$el)
	}

	addSource(val) {
		const jsonObj = new GeoJSON().readFeatures(val);
		this.models.geoJsonSource.clear();
		this.models.geoJsonSource.addFeatures(jsonObj);

	}

	updatePosition(val: any) {
		if (val) {
			this.models.map.getView().animate({
				center: val, // 新的中心坐标
				zoom: 16,        // 新的缩放级别
				duration: 3000   // 动画持续时间（毫秒）
			});
		}
		this.setMarker(val);
	}

	setMarker(point) {
		let feature = new Feature({
			geometry: new Point(point),
			style: pointImageStyle('location')
		})
		this.models.geoJsonSource.addFeature(feature);
	}
}
</script>
<style scoped>
.map0 {
	opacity: 0.8;
	width: 24px;
	height: 24px;
	background: url(../assets/image/tooltip.png) center center no-repeat;
	background-size: 16px 16px;
	position: absolute;
	right: 60px;
	top: 10px;
	z-index: 200;
	cursor: pointer;
}

.map1 {
	opacity: 0.5;
	width: 250px;
	height: 40px;
	background: #000 center center no-repeat;
	position: absolute;
	right: 0px;
	top: 0px;
	z-index: 200;
	cursor: pointer;
}

.mapbox {
	width: 320px;
	height: 60px;
	display: flex;
	flex-wrap: nowrap;
	justify-content: space-between;
}

.mapbox li {
	width: 100px;
	height: 50px;
	margin: 5px 0;
	display: block;
	position: relative;
	cursor: pointer;
}

.mapbox li .on {
	height: 16px;
	width: 100px;
	background-color: rgba(0, 0, 0, 0.3);
	color: #fff;
	font-size: 12px;
	position: absolute;
	bottom: 0;
	left: 0;
	display: none;
	text-align: center;
}

.mapbox li:hover .on {
	display: block;
}

.activeStyle {
	width: 100px;
	height: 50px;
	border: 1px solid #f00;
}

.container {
	border: 1px solid #42B983;
	position: relative;
}

.controlbox {
	opacity: 0.8;
	position: absolute;
	z-index: 10000;
	bottom: 200px;
	width: 18px;
	padding: 5px 7px;
	height: 220px;
	right: 20px;
	border: 1px solid #ccc;
	border-radius: 4px;
	cursor: pointer;
	display: flex;
	align-content: space-between;
	flex-direction: column;
	background-color: #fff;
}

.getlength0 {
	width: 18px;
	height: 30px;
	background: url(../assets/image/getnlength.png) center center no-repeat;
	background-size: 16px 16px;
}

.getarea0 {
	width: 18px;
	height: 30px;
	background: url(../assets/image/getarea.png) center center no-repeat;
	background-size: 16px 16px;
}

.ol-popup {
	padding: 30px 15px 15px; /* 顶部留更多空间 */
    position: absolute;
    background-color: rgba(28, 181, 51, 0.9);
    padding: 15px;
    border-radius: 10px;
    border: 2px solid #fff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.3);
    min-width: 220px;
    max-width: 300px;
	/* 默认隐藏 */
}

.ol-popup:after {
	content: "";
	position: absolute;
	bottom: -10px;
	left: 50%;
	margin-left: -10px;
	border-width: 10px;
	border-style: solid;
	border-color: white transparent transparent transparent;
}

.juxing {
	width: 18px;
	height: 30px;
	background: url(../assets/image/juxing.png) center center no-repeat;
	background-size: 16px 16px;
}

.stopdraw {
	width: 18px;
	height: 30px;
	background: url(../assets/image/stopdraw.png) center center no-repeat;
	background-size: 16px 16px;
}

.clear {
	width: 18px;
	height: 30px;
	background: url(../assets/image/clear.png) center center no-repeat;
	background-size: 16px 16px;
}

.ol-popup-closer:hover {
    color: #ff4444;
}
.ol-popup-closer {
    position: absolute;
    top: 5px;
    right: 10px;
    text-decoration: none;
    color: white;
    font-size: 18px;
    font-weight: bold;
    z-index: 5000;
    line-height: 1; /* 防止符号垂直偏移 */
}

.ol-popup-closer:after {
	content: "✖";
	font-size: 16px;
	color: #999;
}

.ol-popup-closer:hover:after {
	color: #666;
}

/* 在 style 部分添加 */
.data-table {
	width: 100%;
	border-collapse: collapse;
	margin-top: 10px;
}

.data-table th,
.data-table td {
	border: 1px solid #ddd;
	padding: 8px;
	text-align: left;
}

.data-table th {
	background-color: #f5f7fa;
}

.ol-popup:after, .ol-popup:before {
    border-top-color: rgba(255, 255, 255, 0.9);
}
.ol-popup[style*="display: block"] {
  display: block !important;
  opacity: 1 !important;
}
</style>
